import logging
import random
from typing import Sequence

from celery import shared_task
from django.core.cache import cache


logger = logging.getLogger(__name__)


@shared_task(
    name="home.cache_invalidator.delayed_delete",
    autoretry_for=(Exception,),
    retry_backoff=True,
    retry_jitter=True,
    max_retries=3,
)

def delayed_delete(keys: Sequence[str]) -> int:
    """
    延时二次删除（幂等）。
    :param keys: 需要再次删除的一组缓存键
    :return: 实际删除尝试的键数量（用于观察日志，不依赖返回值）
    """
    ok = 0
    for key in keys:
        try:
            cache.delete(key)
            ok += 1
        except Exception as exc:  # pragma: no cover - 保底日志
            logger.exception("delayed_delete fail key=%s", key)
            raise exc
    logger.info("delayed_delete ok count=%s keys_sample=%s", ok, list(keys)[:5])
    return ok



def schedule_delayed_delete(
    keys: Sequence[str], base_delay_seconds: int = 5, jitter_seconds: int = 3
) -> None:
    """
    该函数用于投递一个延时删除任务。它通过在基础延迟时间上增加随机抖动，避免大量任务在同一时刻执行，从而防止系统负载过高。最终调用 delayed_delete 异步执行实际的删除操作。
    投递延时任务。延时 = base + [0, jitter] 抖动，避免热点时刻集中触发。
    """
    delay = base_delay_seconds + max(0, random.randint(0, jitter_seconds))
    """
    """
    delayed_delete.apply_async(args=[list(keys)], countdown=delay)

